package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.UserStatusEnum;
import cn.huiyunche.base.service.enums.UserTypeEnum;
import cn.huiyunche.base.service.interfaces.UserJourneyService;
import cn.huiyunche.base.service.mappers.SUserMapper;
import cn.huiyunche.base.service.mappers.ext.UserJourneyExtMapper;
import cn.huiyunche.base.service.model.CJourney;
import cn.huiyunche.base.service.model.SUser;
import cn.huiyunche.base.service.model.SUserExample;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service

public class UserJourneyServiceImpl implements UserJourneyService {

    @Autowired
    private UserJourneyExtMapper journeyExtMapper = null;

    @Autowired
    private SUserMapper userMapper = null;

    @Override
    public List<CJourney> selectTodayJourneyFromAllOnlineUsers() {
        Calendar todayBegin = Calendar.getInstance();
        todayBegin.set(Calendar.HOUR_OF_DAY, 0);
        todayBegin.set(Calendar.MINUTE, 0);
        todayBegin.set(Calendar.SECOND, 0);

        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println(sdf.format(todayBegin.getTime()) + "--------" + sdf.format(todayEnd.getTime()));

        //获取在线用户当天最后行程
        List<CJourney> journeys = new ArrayList<>();
        SUserExample search = new SUserExample();
        search.createCriteria().andUserTypeEqualTo(UserTypeEnum.DRIVER.getValue()).andUserStatusEqualTo(UserStatusEnum.T.getValue());
        List<SUser> users = userMapper.selectByExample(search);
        if (CollectionUtils.isNotEmpty(users)) {
            for (int i = 0; i < users.size(); i++) {
                SUser user = users.get(i);
                CJourney journey = this.selectAtLastJourney(user.getId(), sdf.format(todayBegin.getTime()), sdf.format(todayEnd.getTime()));
                if (journey != null) {
                    journeys.add(journey);
                }
            }
        }

        return journeys;
    }

    @Override
    public CJourney selectAtLastJourney(Long userId, String beginTime, String endTime) {
        return journeyExtMapper.selectAtLastJourney(userId, beginTime, endTime);
    }

}
